# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/7/21 下午5:28
File: reboot_monitor.py
"""

import os
import json
import time
import socket
from dingtalk_bot import DingTalkBot

# 文件路径定义
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_DIR = os.path.join(BASE_DIR, "..", "config")

REBOOT_CONFIG_FILE = os.path.join(CONFIG_DIR, "reboot_config.json")
DINGTALK_CONFIG_FILE = os.path.join(CONFIG_DIR, "dingtalk_config.json")

def load_reboot_config():
    """加载重启检测配置"""
    try:
        with open(REBOOT_CONFIG_FILE, "r", encoding="utf-8") as f:
            config = json.load(f)
        return config
    except Exception as e:
        print(f"读取重启配置失败：{e}")
        return {"enabled": False}

def load_dingtalk_config(group_name):
    """从 dingtalk_config.json 中加载指定群的配置"""
    try:
        with open(DINGTALK_CONFIG_FILE, "r", encoding="utf-8") as f:
            configs = json.load(f)
        for config in configs:
            if config.get("group_name") == group_name:
                return config
        raise ValueError(f"未找到钉钉群组：{group_name}")
    except Exception as e:
        print(f"读取钉钉配置失败：{e}")
        return {}

def send_reboot_notification(dingtalk_config, pc_name):
    """发送重启通知到钉钉群"""
    try:
        bot = DingTalkBot(dingtalk_config)

        # 获取当前时间
        now = time.localtime()
        date_str = time.strftime("%Y年%m月%d日 %H时%M分%S秒", now)

        # 构建消息内容
        message = f"{date_str}\n烤机电脑: {pc_name}\n重启了，请及时处理！"

        # 发送文本消息并 @所有人
        result = bot.send_text(content=message, at_mobiles=[])
        print("钉钉消息发送结果：", result)
    except Exception as e:
        print(f"发送钉钉消息失败：{e}")

def main():
    # 1. 加载重启检测配置
    reboot_config = load_reboot_config()
    if not reboot_config.get("enabled", False):
        print("重启检测未启用")
        return

    push_group = reboot_config.get("push_group")
    if not push_group:
        print("未配置推送钉钉群")
        return

    pc_name = reboot_config.get("pc_name", socket.gethostname())

    # 2. 加载钉钉群配置
    dingtalk_config = load_dingtalk_config(push_group)
    if not dingtalk_config:
        print("钉钉群配置为空，无法发送消息")
        return

    # 3. 发送钉钉消息
    print("发送重启通知中...")
    time.sleep(60)
    send_reboot_notification(dingtalk_config, pc_name)

if __name__ == "__main__":
    main()